from rest_framework import serializers
from .models import DicType, DicItem, Platform, Menu

# 字典类型序列化器
class DicTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = DicType
        fields = ['id', 'dic_type_id', 'dic_type_code', 'dic_type_name', 'description','remark','sort_num']
        read_only_fields = ['id']

# 字典项序列化器
class DicItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = DicItem
        fields = ['id', 'dic_type_id', 'dic_item_id', 'dic_item_code', 'dic_item_name', 'description','remark', 'parent_id', 'parent_dic_item_id', 'level_num','sort_num']
        read_only_fields = ['id']

class RecursiveSerializer(serializers.Serializer):
    # 递归序列化器，用于处理嵌套关系
    def to_representation(self, value):
        serializer = self.parent.parent.__class__(value, context=self.context)
        return serializer.data

# 字典项树形结构序列化器
class DicItemTreeSerializer(serializers.ModelSerializer):
    children = RecursiveSerializer(many=True, read_only=True)
    class Meta:
        model = DicItem
        fields = ['id', 'dic_type_id', 'dic_item_id', 'dic_item_code', 'dic_item_name', 'description','remark', 'parent_id', 'parent_dic_item_id', 'level_num','sort_num', 'children']
        read_only_fields = ['id']

# 包含字典项的字典类型序列化器
class DicTypeItemSerializer(serializers.ModelSerializer):
    items = serializers.SerializerMethodField()
    class Meta:
        model = DicType
        fields = ['id', 'dic_type_id', 'dic_type_code', 'dic_type_name', 'description','remark','sort_num', 'items']
        read_only_fields = ['id']
    def get_items(self, obj):
        items = DicItem.objects.filter(dic_type_id=obj.dic_type_id, parent_id=None).order_by('sort_num')
        serializer = DicItemTreeSerializer(items, many=True, context=self.context)
        return serializer.data

# 平台序列化器
class PlatformSerializer(serializers.ModelSerializer):
    class Meta:
        model = Platform
        fields = ['id', 'platform_id', 'platform_code', 'platform_name', 'description', 'version', 'homepage', 'app_download_url', 'remark', 'sort_num']
        read_only_fields = ['id']

# 菜单序列化器
class MenuSerializer(serializers.ModelSerializer):
    children = RecursiveSerializer(many=True, read_only=True)
    class Meta:
        model = Menu
        fields = ['id', 'name', 'url', 'icon', 'menu_type', 'parent_id', 'level_num','sort_num', 'platform_id', 'children']
        read_only_fields = ['id']
        ordering = ['sort_num']